import {imBindUser} from '@/api/im'
import {ElNotification} from "element-plus";
import store from "@/store";


const IM = {
    isBlur: false,
    titleInit: document.title,
    isShine: false,
    isLeave: false,
    isOpen: false,
    timerId: null,
    socket: null,
    CHECK_TIME: process.env.NODE_ENV === "development" ? 1000 * 5 : 1000 * 10,
    WS_URL: 'wss://xiangmu.xinyunweb.com/wss',
    KEY_ENUM: {
        INIT: "init",
        MSG: "msg",
        INIT_TITLE: '欢迎回来'
    },
    onMessageEvent: {},
    toast({msg, duration = 0, title = '收到新的消息', type = 'success'}) {
        ElNotification({
            title,
            duration,
            message: msg,
            showClose: true,
            type,
        })
    },
    bindEvent(name, func) {
        this.onMessageEvent[name] = func
    },
    removeEvent(name) {
        if (!this.onMessageEvent.hasOwnProperty(name)) return
        delete this.onMessageEvent[name]
    },
    updateUnReadCount() {
        store.dispatch('app/initUnReadCount').catch(null)
    },
    onMessage(data) {
        if (!data.msg) return
        this.updateUnReadCount()
        this.toast({msg: data.msg})
        const {onMessageEvent} = this
        for (const key in onMessageEvent) {
            const func = onMessageEvent[key]
            func && func(data)
        }
        if (this.isBlur) this.startNotification()
    },
    clearTimeout() {
        if (!this.timerId) return
        clearTimeout(this.timerId)
        this.timerId = null
    },
    heartCheck() {
        if (!this.socket || !this.isOpen || this.isLeave) {
            return this.clearTimeout()
        }
        this.timerId = setTimeout(() => {
            console.log('发送心跳检测')
            this.socket.send(JSON.stringify({type: 'heartCheck', msg: '心跳检测'}))
            this.heartCheck()
        }, this.CHECK_TIME)
    },
    init(retry = false) {
        if (store.getters.isDev) return console.warn('开发环境:IM不需要初始化')
        if (!retry) this.bindWindEvent()
        this.socket = new WebSocket(this.WS_URL)
        this.socket.addEventListener('open', ev => {
            this.isOpen = true
            this.heartCheck()
            this.updateUnReadCount()
            console.warn('WS is Open', ev)
        })
        this.socket.addEventListener('message', ev => {
            console.warn('收到的消息==>', ev.data)
            try {
                const data = JSON.parse(ev.data)
                if (!data.hasOwnProperty('type')) return
                const {type} = data
                const {KEY_ENUM} = this
                if (type === KEY_ENUM.INIT) return this.bindUser(data, retry)
                if (type === KEY_ENUM.MSG) return this.onMessage(data)
            } catch (e) {

            }
        })
        this.socket.addEventListener('close', ev => {
            console.warn('连接关闭', ev)
            this.isOpen = false
            this.socket = null
            this.clearTimeout()
        })
        this.socket.addEventListener('error', error => {
            console.log('error=>', error)
        })
    },
    async bindUser(data, retry = false) {
        const {client_id} = data
        const resp = await imBindUser({client_id})
        const {code, msg} = resp
        if (!retry) this.toast({title: this.KEY_ENUM.INIT_TITLE, msg, duration: 2000})
        if (code !== 1) return
        store.commit('app/changeBindStatus', code === 1)
    },
    closeConnect() {
        this.socket.close()
    },
    logout() {
        this.closeConnect()
        document.onvisibilitychange = null
    },
    clearNotification() {
        if (this.interval) clearInterval(this.interval)
        this.interval = null
        document.title = this.titleInit
    },
    bindWindEvent() {
        document.onvisibilitychange = () => {
            // this.clearTimeout()
            if (document.visibilityState === 'hidden') {
                // this.isLeave = true
                // return this.closeConnect()
                return this.isBlur = true
            }
            this.isBlur = false
            this.clearNotification()
            // this.isLeave = false
            // this.init(true)
        }
    },
    startNotification() {
        if (this.interval) return
        this.interval = setInterval(() => {
            if (this.isShine) {
                document.title = '【你有新消息】';
            } else {
                document.title = '【　　　　　】';
            }
            this.isShine = !this.isShine
        }, 500);
    },
}

export default IM
